package com.wry.sharding.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * <h1> 按时间范围分片 <h1>
 *
 * @author wry
 * @since 2025/1/14 17:12
 */
public class OrderRangeAlgorithm implements PreciseShardingAlgorithm<LocalDateTime>, RangeShardingAlgorithm<LocalDateTime> {

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<LocalDateTime> preciseShardingValue) {
        return "";
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTableNames, RangeShardingValue<LocalDateTime> shardingValues) {
        Collection<String> result = new LinkedHashSet<>();
//        // 获取时间范围（起始时间和结束时间）
//        LocalDateTime lowerBound = shardingValues.getValueRange().lowerEndpoint();  // 起始时间
//        LocalDateTime upperBound = shardingValues.getValueRange().upperEndpoint();  // 结束时间
//
//        // 格式化年份和月份
//        int startYear = lowerBound.getYear();
//        int startMonth = lowerBound.getMonthValue();
//        int endYear = upperBound.getYear();
//        int endMonth = upperBound.getMonthValue();
//
//        // 根据起始年份和月份、结束年份和月份进行分表
//        for (int year = startYear; year <= endYear; year++) {
//            for (int month = (year == startYear) ? startMonth : 1; month <= (year == endYear ? endMonth : 12); month++) {
//                String tableName = String.format("oms_order_%d_%02d", year, month);
//                if (availableTableNames.contains(tableName)) {
//                    result.add(tableName);
//                }
//            }
//        }
        if (availableTableNames.contains("oms_order202501")) {
            result.add("oms_order202501");
        } else {
            result.add("oms_order_goods_item202501");
        }
        return result;
    }
}
